from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, reverse
from crm import models


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 白名单
        url = request.path_info
        if url in [reverse('crm:login'), reverse('crm:reg')]:
            return

        if url.startswith('/admin'):
            return

        # 获取登陆状态
        is_login = request.session.get('is_login')

        # 查询用户对象
        user_obj = models.UserProfile.objects.filter(pk=request.session.get('user_id')).first()
        if not user_obj or is_login != '1':
            # 跳转登陆页面
            return redirect('crm:login')

        request.user_obj = user_obj  # request.user
